package app.service.xml;

import static app.constants.CollabVizConstants.*;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.OutputStreamWriter;

import org.apache.commons.lang.StringUtils;
import org.exolab.castor.mapping.Mapping;
import org.exolab.castor.mapping.MappingException;
import org.exolab.castor.xml.MarshalException;
import org.exolab.castor.xml.Marshaller;
import org.exolab.castor.xml.Unmarshaller;
import org.exolab.castor.xml.ValidationException;
import org.xml.sax.InputSource;

/**
 * This class can be used to map between in-memory classes and xml. Uses the castor lib to do that. 
 */

public class XMLMarshaler {

	/**
	 * Represents the mapping between the xml structure and the java object. 
	 */
	static Mapping mappingConfig;

	static{
		mappingConfig = new Mapping();
	}

	/**
	 * @param filePath
	 * @return null if file does not exist. 
	 * @throws CollabVizException
	 */
	public static Object unmarshall(String filePath)  {
		Unmarshaller unmarshal;
		try {
			unmarshal = new Unmarshaller(mappingConfig);
			return unmarshal.unmarshal(new InputSource(new FileReader(filePath)));
		} catch (MappingException e) {
			throw new Error(e);
		} catch (MarshalException e) {
			throw new Error(e);
		} catch (ValidationException e) {
			throw new Error(e);
		} catch (FileNotFoundException e) {
			throw new Error(e);
		}
	}

	public static void marshall(String filePath, Object obj) {
		Marshaller marshall;
		try {
			marshall = new Marshaller(new OutputStreamWriter(new FileOutputStream(filePath)));
			marshall.setMapping(mappingConfig);
			marshall.marshal(obj);
		} catch (FileNotFoundException e) {
			throw new Error(e);
		} catch (IOException e) {
			throw new Error(e);
		} catch (MappingException e) {
			throw new Error(e);
		} catch (MarshalException e) {
			throw new Error(e);
		} catch (ValidationException e) {
			throw new Error(e);
		}
	}
}
